#!/usr/bin/perl -w
use strict;
use Bio::TreeIO;
use Getopt::Long;

my $format = 'newick';
my $debug;
GetOptions('f|format:s' => \$format,
	   'v|verbose|debug!' => \$debug,
	   );

my ($treefile,$candidate_dir) = @ARGV;

my $in = Bio::TreeIO->new(-format => $format,
			  -file   => $treefile);
while( my $t = $in->next_tree ) {
    my %matrix;
    my @nodes;
    for my $node ( grep { $_->is_Leaf } $t->get_nodes ) {
	next if $node->id =~ /\//;
	push @nodes, $node;
    }
    for my $n ( @nodes ) {
	for my $n2 ( @nodes ) {
	    next if $n2->id eq $n->id;
	    $matrix{$n->id}->{$n2->id} = $t->distance(-nodes => [$n,$n2]);
	    #$matrix{$n2->id}->{$n->id} = $t->distance(-nodes => [$n2,$n]);
	    # printf "%s %s -- %s\n", $n->id, $n2->id, $t->distance(-nodes => [$n,$n2]);
	}
	last if $debug;
    }
    for my $n ( keys %matrix ) {
	# make a sorted array of all the taxa which are in tree, based on their distance from $n	
	# get back an array (stored in @p) which will have an entry for every other node
	# (besides the one I am at e.g. $n)
	# The array will have the contents 
	# (   [NODE_NAME, DISTANCE_FROM_N],
	#     [NODE_NAME, DISTANCE_FROM_N]
	# so for a tree that looks like
	#   (A:10,(B:5,C:7):2);
	# if $n='A'
	# I would get ( [ 'B', 7],
	#		[ 'C', 19])
	# The list is ordered by the distance, starting with smallest
	
	my @p = sort { $a->[1] <=> $b->[1] } map { [ $_, $matrix{$n}->{$_} ] } keys %{$matrix{$n}};
	# I only want the closest one, which will be the 1st item;
	my ($closest) = shift @p;
	my ($c, $closest_dist) = @$closest;
	`bl2seq -D 1 -p blastn -i $candidate_dir/$n.fa -j $candidate_dir/$c.fa -o $candidate_dir/$n-vs-$c.BLASTN.tab -e 1e-5`;
	`perl ../TE_scripts/search_TcMariner.pl -o $candidate_dir\_Full_TcMariner -db $candidate_dir/$n.fa -t $candidate_dir/$n-vs-$c.BLASTN.tab`;
	#`fasta36 -m 8C $candidate_dir/$n.fa $candidate_dir/$c.fa > $candidate_dir/$n-vs-$c.FASTA.tab`;
    }
}
